#!/usr/bin/env python

import sys, os
import getopt

Version = 3.2

#Fields:
tmpfile = ".response"    #Temporary file to store http response into.
file = None              #User-specified filename to upload.
dir = None               #User-specified directory name to upload.
ext = None               #User-specified file name extension to upload.

def PrintUsage():
    print ""
    print "Usage: " + sys.argv[0] + " -h | -f <file> | -d <dir> -e <ext>"
    print "    -h            Print this help."
    print "    -f <file>     Upload single file and print link."
    #print "    -d <dir>      Upload directory. Must specify file extension to upload with -e <ext>."
    #print "    -e <ext>      Only upload files with <ext>. Used with the -d option."
    print ""
    print "Examples:"
    print "    " + sys.argv[0] + " -f MyImage.png"
    print "    " + sys.argv[0] + " -d MyDirectory -e jpg"
    print ""
    print "PetaUpload " + str(Version) + " by Oytun Ozdemir <oytunozdemir@gmail.com>"

def UploadFile(file):
    #Execute curl:
    cmd = "curl -H Expect: -F file[]=\"@" + file + "\" -F submit=true -# \"http://www.petaimg.com/index.php\" > " + tmpfile;
    os.system(cmd)
    #Read tmp file and find image link:
    tmp = open(tmpfile, "r").read()
    i1 = tmp.find("<b>Image:</b>")
    i2 = tmp.find("\" target=\"_blank\">")
    link = tmp[i1 + 23 : i2]
    #Remove tmp file:
    os.system("rm -f " + tmpfile)
    #Return link:
    return link


def Main():
    try:
        if len(sys.argv) < 2: #If no arguments are given:
            PrintUsage()
            exit()
        opts = getopt.getopt(sys.argv[1:], "hf:")
        for i in opts[0]:
            if i[0] == "-h":
                PrintUsage()
            elif i[0] == "-f":
                file = i[1]
                #print "Uploading file: " + file + "..."
                link = UploadFile(file)
                #print "File: " + file 
                print link
           
    except getopt.GetoptError, e:
        print e
        PrintUsage()
        exit()

Main()
